package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javax.validation.Validator;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.ThridApiResponse;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.UploadUserRequest;
import com.ruoyi.system.service.IPCabinetService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;


/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl  extends ServiceImpl<SysUserMapper,SysUser> implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);



    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    protected Validator validator;
    @Autowired
    private IPCabinetService cabinetService;
    /**
     * 根据条件分页查询用户列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user)
    {
        return baseMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user)
    {
        return baseMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user)
    {
        return baseMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {
        return baseMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId)
    {
        return baseMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName)
    {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     * 
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     * 
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        // 新增用户信息
        int rows = baseMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);

        //下发人员
        //sendUserInfo(user);

        return rows;
    }
    /**
     * 下发人员信息到设备
     * @return 下发结果
     */
    public boolean sendUserInfo(SysUser user) {
        // 1. 获取设备信息
        QueryWrapper<PCabinet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", user.getSid());
        PCabinet deviceInfo = cabinetService.getOne(queryWrapper);
        if (deviceInfo == null) {
            log.error("设备不存在，: {}", deviceInfo.getCode());
            throw new ServiceException(deviceInfo.getCode()+"不存在");
        }

        Map<String, Object> userInfo=new HashMap<>();
        // 2. 构建设备URL

        String apiUrl = "http://"+deviceInfo.getCabinetIp() + "/device/addUser";

        // 3. 添加设备SID到请求参数
        userInfo.put("SID", user.getSid());
        userInfo.put("UNo", user.getUno());              // 人员编号
        userInfo.put("UName", user.getUserName());                 // 人员姓名
        userInfo.put("CardNo", user.getCardNo());          // 人员卡号
        userInfo.put("UpdateTime", user.getUpdateTime()); // 更新时间
        userInfo.put("faceImage", user.getFaceImage());       // Base64编码的人脸照片
        userInfo.put("pass", user.getPassword());               // 密码
        userInfo.put("userType", user.getUserType());
        // 4. 发送请求
        try {
            log.info("向设备[{}]下发人员信息，人员编号: {}",
                    deviceInfo.getCode(), userInfo.get("UNo"));

            HttpResponse response = HttpRequest.post(apiUrl)
                    .body(JSONUtil.toJsonStr(userInfo))
                    .contentType("application/json")
                    .timeout(10000) // 下发人员可能包含图片，延长超时时间
                    .execute();

            if (response.isOk()) {
                String body = response.body();
                // 解析响应
                R<Map> resultObj = JSONUtil.toBean(body, R.class);
                if (resultObj != null && resultObj.getCode() == 200) {
                    Map data = resultObj.getData();
                    if (data != null && "SUCCESS".equals(data.get("bizCode"))) {
                        log.info("设备[{}]人员信息下发成功，人员编号: {}",
                                deviceInfo.getCode(), userInfo.get("UNo"));
                        return true;
                    } else {
                        log.error("设备[{}]人员信息下发失败，业务码: {}, 消息: {}",
                                deviceInfo.getCode(),
                                data != null ? data.get("bizCode") : "null",
                                data != null ? data.get("bizMsg") : "null");
                    }
                } else {
                    log.error("设备[{}]人员信息请求失败，响应码: {}",
                            deviceInfo.getCode(),
                            resultObj != null ? resultObj.getCode() : "null");
                }
            } else {
                log.error("设备[{}]HTTP请求失败，状态码: {}",
                        deviceInfo.getCode(), response.getStatus());
            }
        } catch (Exception e) {
            log.error("设备[{}]人员信息请求异常: {}", deviceInfo.getCode(), e.getMessage(), e);
        }

        return false;
    }
    /**
     * 注册用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user)
    {
        return baseMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user)
    {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return baseMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds)
    {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user)
    {
        return baseMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user)
    {
        return baseMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     * 
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar)
    {
        return baseMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 修改用户头像
     *
     * @param userId 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, String avatar)
    {

        return baseMapper.updateUserAvatarById(userId, avatar) > 0;
    }

    @Override
    public int exchangeRole(Long id) {

        SysUser sysUser = baseMapper.selectById(id);
        sysUser.setRoles(SecurityUtils.getLoginUser().getUser().getRoles());
        sysUser.setRoleIds(SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).toArray(Long[]::new));
        return updateUser(sysUser);
    }

    @Override
    public void newInsertUser(UploadUserRequest vo) {

        SysUser oldSysUser = baseMapper.selectUserByUno(vo.getUNo());
        if (oldSysUser == null) {
            // 2. 不存在则新增
            SysUser sysUser =new SysUser();
            BeanUtil.copyProperties(vo, sysUser);
            sysUser.setSid(vo.getSid());
            sysUser.setPassword(vo.getPass());
            sysUser.setNickName(vo.getUName());
            sysUser.setUserName(vo.getUName());
            sysUser.setDevId(vo.getDevId());
            sysUser.setUno(vo.getUNo());
            sysUser.setCardNo(vo.getCardNo());
            if(StringUtils.isNotBlank(vo.getUpdateTimes())){
                sysUser.setUpdateTime(DateUtils.dateTime("yyyyMMdd HH:mm:ss",vo.getUpdateTimes()));
            }
            baseMapper.insert(sysUser);
        } else {
            // 3. 存在则比较 UpdateTime

            if (StringUtils.isNotBlank(vo.getUpdateTimes()) && !oldSysUser.getUpdateTime().equals(DateUtils.dateTime("yyyyMMdd HH:mm:ss",vo.getUpdateTimes()))) {
                // 4. UpdateTime 不同则更新（使用 MyBatis-Plus 的 updateById 方法）
                oldSysUser.setSid(vo.getSid());
                oldSysUser.setDevId(vo.getDevId());
                oldSysUser.setUserName(vo.getUName());
                oldSysUser.setNickName(vo.getUName());
                oldSysUser.setCardNo(vo.getCardNo());
                oldSysUser.setUpdateTime(DateUtils.dateTime("yyyyMMdd HH:mm:ss",vo.getUpdateTimes()));
                oldSysUser.setFaceImage(vo.getFaceImage());
                oldSysUser.setPassword(vo.getPass());
                oldSysUser.setUserType(vo.getUserType());
                baseMapper.updateById(oldSysUser);
            }
        }
    }

    // 注入线程池和重试模板
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;



    @Override
    public void pullDeviceUser() {
        log.info("开始拉取所有设备上的人员信息");
        List<PCabinet> list = cabinetService.list();

        // 使用CompletableFuture并行处理每个设备
        List<CompletableFuture<Void>> futures = list.stream()
                .map(pcabinet -> CompletableFuture.runAsync(() -> {
                    try {
                        processDevice(pcabinet.getCode());
                    } catch (Exception e) {
                        log.error("处理设备{}出错: {}", pcabinet.getCode(), e.getMessage(), e);
                    }
                }, taskExecutor))
                .collect(Collectors.toList());

        // 等待所有任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        log.info("所有设备人员信息拉取完成");
    }

    /**
     * 处理单个设备
     */
    private void processDevice(String sid) {
        // 获取设备信息
        PCabinet deviceInfo = getDeviceInfo(sid);
        if (deviceInfo == null) {
            log.error("设备不存在: {}", sid);
            return;
        }

        // 获取设备上的所有用户ID
        List<String> userNos = fetchUserNosFromDevice(deviceInfo);
        if (userNos.isEmpty()) {
            log.info("设备{}上没有用户", sid);
            return;
        }

        // 批量获取用户详细信息
        fetchUserDetailsInBatch(deviceInfo, userNos);
    }

    /**
     * 获取设备信息
     */
    private PCabinet getDeviceInfo(String sid) {
        QueryWrapper<PCabinet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", sid);
        return cabinetService.getOne(queryWrapper);
    }

    /**
     * 从设备获取所有用户编号（移除重试逻辑）
     */
    private List<String> fetchUserNosFromDevice(PCabinet deviceInfo) {
        String apiUrl = buildApiUrl(deviceInfo, "/device/getAllUser");
        Map<String, String> requestData = new HashMap<>();
        requestData.put("SID", deviceInfo.getCode());

        try {
            log.info("获取{}柜人员列表，url:{} 参数:{}", deviceInfo.getCode(), apiUrl, requestData);
            HttpResponse response = sendRequest(apiUrl, requestData);

            if (response.isOk()) {
                String body = response.body();
                ThridApiResponse resultObj = JSONUtil.toBean(body, ThridApiResponse.class);
                log.info("bizContent type: {}", resultObj.getBizContent().getClass());
                if ("SUCCESS".equals(resultObj.getBizCode()) && resultObj.getBizContent() instanceof JSONArray) {
                    JSONArray contentArray = (JSONArray) resultObj.getBizContent();
                    return contentArray.stream()
                            .map(item -> ((JSONObject) item).getStr("UNo"))
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                }
            }


            return Collections.emptyList();
        } catch (Exception e) {
            log.error("获取设备{}用户列表异常: {}", deviceInfo.getCode(), e.getMessage(), e);
            return Collections.emptyList(); // 统一返回空列表，避免上层空指针
        }
    }

    /**
     * 批量获取用户详细信息（移除重试逻辑）
     */
    private void fetchUserDetailsInBatch(PCabinet deviceInfo, List<String> userNos) {
        if (userNos.isEmpty()) {
            log.info("设备{}无待获取的用户信息", deviceInfo.getCode());
            return;
        }

        String apiUrl = buildApiUrl(deviceInfo, "/device/getUser");

        // 并发获取每个用户的详细信息（保留并发逻辑，仅移除重试）
        List<CompletableFuture<Void>> futures = userNos.stream()
                .map(uno -> CompletableFuture.runAsync(() -> {
                    Map<String, String> requestData = new HashMap<>();
                    requestData.put("SID", deviceInfo.getCode());
                    requestData.put("UNo", uno);
                    try {
                        log.info("获取{}柜编号{}人员信息，url:{} 参数:{}",
                                deviceInfo.getCode(), uno, apiUrl, requestData);
                        HttpResponse response = sendRequest(apiUrl, requestData);

                        if (response.isOk()) {
                            String body = response.body();
                            ThridApiResponse resultObj = JSONUtil.toBean(body, ThridApiResponse.class);

                            if ("SUCCESS".equals(resultObj.getBizCode()) &&
                                    resultObj.getBizContent() instanceof JSONObject) {

                                JSONObject content = (JSONObject) resultObj.getBizContent();
                                UploadUserRequest userRequest =new UploadUserRequest();
                                userRequest.setSid(content.getStr("SID"));
                                userRequest.setDevId(content.getStr("DevId"));
                                userRequest.setUNo(content.getStr("UNo"));
                                userRequest.setUName(content.getStr("UName"));
                                userRequest.setCardNo(content.getStr("CardNo"));
                                userRequest.setUpdateTimes(content.getStr("UpdateTime"));
                                userRequest.setFaceImage(content.getStr("faceImage"));
                                userRequest.setPass(content.getStr("pass"));
                                userRequest.setUserType(content.getStr("userType"));
                                log.info("编号{}人员信息{}", uno,userRequest);
                                newInsertUser(userRequest);
                            }
                        }
                    } catch (Exception e) {
                        log.error("获取设备{}用户{}详情异常: {}",
                                deviceInfo.getCode(), uno, e.getMessage(), e);
                    } // 移除 retryTemplate，直接捕获异常
                }, taskExecutor))
                .collect(Collectors.toList());

        // 等待所有任务完成，添加异常处理
        try {
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(); // 使用 get() 捕获 InterruptedException
        } catch (InterruptedException e) {
            log.error("并发处理被中断: {}", e.getMessage());
            Thread.currentThread().interrupt(); // 恢复中断状态
        } catch (ExecutionException e) {
            log.error("并发处理失败: {}", e.getCause().getMessage());
        }
    }
    /**
     * 构建设备API URL
     */
    private String buildApiUrl(PCabinet deviceInfo, String path) {
        return "http://" + deviceInfo.getCabinetIp() + ":" +
                deviceInfo.getCabinetPort() + path;
    }

    /**
     * 发送HTTP请求
     */
    private HttpResponse sendRequest(String apiUrl, Map<String, String> requestData) throws IOException {
        return HttpRequest.post(apiUrl)
                .body(JSONUtil.toJsonStr(requestData))
                .contentType("application/json")
                .timeout(5000)
                .execute();
    }

    /**
     * 重置用户密码
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user)
    {
        return baseMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     * 
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        return baseMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     * 
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     * 
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return baseMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     * 
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds)
    {
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return baseMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = baseMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    deptService.checkDeptDataScope(user.getDeptId());
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    baseMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    baseMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<SysUser> getUsersByRoleId(Long roleId) {
        return baseMapper.selectUsersByRoleId(roleId);
    }

}
